﻿using System;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Collections.Generic;
using Conusic;
using Conusic.Properties;

namespace ConusicUI
{
    /// <summary>
    /// Description of Main.
    /// </summary>
    public sealed partial class Main : Form, IPostGraffitiCommand
    {
        public Main()
        {
            InitializeComponent();
            SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
            this.Text = String.Format("Conusic {0}", Application.ProductVersion);
        }

        private void PostGraffiti(bool directload)
        {
            if (this.profileSelectorGraffiti.SelectedProfile != null)
            {
                byte[] file = GetGraffityFile(directload);

                if (file != null)
                {
                    VkontakteButtonPostGraffiti.Enabled = false;
                    this.PostGraffiti(this.profileSelectorGraffiti.SelectedProfile, textBoxGraffitiText.Text, file);
                }
            }
            else
            {
                ErrorReport.ShowPopup("Для отправки граффити необходимо выбрать профиль.", VkontakteButtonPostGraffiti);
            }
        }

        private byte[] GetGraffityFile(bool directLoad)
        {
            byte[] file = null;
            if (!directLoad)
            {
                Stream image = imageEditor1.GetPosterizedImage();
                file = ((MemoryStream)image).ToArray();
            }
            else
            {
                var fileDialog = new OpenFileDialog();
                fileDialog.Filter = "Изображения PNG (*.png)|*.png|Все файлы | *.*";
                fileDialog.Title = "Выберите изображение для прямой загрузки";
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        file = File.ReadAllBytes(fileDialog.FileName);
                    }
                    catch (IOException ex)
                    {
                        ErrorReport.ShowPopup(
                            String.Format("Ошибка чтения файла {0}: {1}", fileDialog.FileName, ex.Message),
                            VkontakteButtonPostGraffiti);
                    }
                }
                else
                {
                    return null;
                }
            }
            return file;
        }

        #region PostGraffiti

        private void PostGraffiti(Profile to, string message, byte[] file)
        {
            if (to == null)
                throw new ArgumentNullException("to");

            VkontakteWallPost.PostGraffitiAsync(to, message, file, this);
        }


        void IPostGraffitiCommand.Execute(Profile id)
        {
            if (this.InvokeRequired)
                this.Invoke((MethodInvoker)delegate { ((IPostGraffitiCommand)this).Execute(id); });
            else
            {
                System.Diagnostics.Process.Start(id.FullUrl);
                VkontakteButtonPostGraffiti.Enabled = true;
            }
        }

        void IPostGraffitiCommand.Fail(Exception exc)
        {
            if (this.InvokeRequired)
                this.Invoke((MethodInvoker)delegate { ((IPostGraffitiCommand)this).Fail(exc); });
            else
            {
                if (exc is CaptchaException)
                {
                    ErrorReport.ShowPopup("Неправильно введены символы с Captcha.", VkontakteButtonPostGraffiti);
                }
                else
                {
                    ErrorReport.Show(exc, this);
                }
                VkontakteButtonPostGraffiti.Enabled = true;
            }
        }

        void IPostGraffitiCommand.Progress(int percent)
        {
            this.Invoke((MethodInvoker)delegate { this.progressBar1.Value = percent; });
        }

        private Captcha tempCaptcha = null;

        public Captcha CaptchaHandler
        {
            get
            {
                if (this.tempCaptcha == null)
                {
                    this.tempCaptcha = new CaptchaDialog(this);
                    return tempCaptcha;
                }
                return tempCaptcha;
            }
            set { tempCaptcha = value; }
        }

        public bool OfficialCheck()
        {
            bool result = false;
            if(this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(()=>OfficialCheck(out result)));
                return result;
            }
            else
            {
                OfficialCheck(out result);
                return result;
            }
        }

        private void OfficialCheck(out bool result)
        {
            var s = MessageBox.Show(
                this,
                @"Отправить графити от имени группы?",
                @"Official",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button1);

            result = s == DialogResult.Yes;
        }

        #endregion



        private void VkontakteButtonPostGraffitiMouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                PostGraffiti(true);
            }
            else if (e.Button == MouseButtons.Left)
            {
                PostGraffiti(false);
            }
        }

        private void ButtonChangeProfileClick(object sender, EventArgs e)
        {
            Settings.Default.SID =  String.Empty;

            this.Hide();

            var authForm = new FormAuth();
            if (authForm.ShowDialog() == DialogResult.OK)
            {
                this.Show();
            }
            else
            {
                this.Close();
            }
        }

    }
}